<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="申请人">
              <select-user-by-dep :multi="false" v-model="queryParam.applyUser"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="会议日期">
              <a-range-picker format="YYYY-MM-DD" v-model="rangeDate" @change="handleChangeRangeDate"></a-range-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="使用用途">
              <j-dict-select-tag type="list" v-model="queryParam.usePurpose" dictCode="meeting_room_use_purpose" placeholder="请选择使用用途"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->

    <!-- table区域-begin -->
    <div style="display: flex; justify-content: end;">
      <p style="width: 70px; height: 30px;background: orange; font-size:10px; margin-right: 30px; color: #ffffff; text-align:center;line-height: 30px;border-radius:2px;">已占用</p>
      <p style="width: 70px; height: 30px;background: gray;font-size: 10px;color:#ffffff; text-align:center;line-height: 30px;border-radius:2px;">暂不可用</p>
    </div>
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:1300}"
        :components="draggableComponent"
        bordered
        rowKey="key"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        class="j-table-force-nowrap"
        :pagination="{ pageSize: 10, current: pageCurrent, total: dataSourceLength}"
        @change="handleTableChange">

        <span slot="location" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">
              查看会议室详情
            </template>
            <a @click="handleShowRoomDetail(record)">{{ text }}</a>
          </a-tooltip>
        </span>
      </a-table>
    </div>

    <erp-meeting-reservation-modal ref="modalForm" @ok="modalFormOk"></erp-meeting-reservation-modal>

    <erp-meeting-room-modal ref="roomModalForm" @ok="modalFormOk"></erp-meeting-room-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ErpMeetingReservationModal from './modules/ErpMeetingReservationModal'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { getAction, deleteAction } from '@/api/manage'
import ErpMeetingRoomModal from './modules/ErpMeetingRoomModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import { filterMultiDictText, initDictOptions } from '@comp/dict/JDictSelectUtil';

var isColSpan = 0 // 单元格合并对比
var isRoomSpan = '' // 单元格合并对比
export default {
  name: 'ErpMeetingReservationList',
  mixins: [JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
  components: {
    ErpMeetingRoomModal,
    ErpMeetingReservationModal,
    SelectUserByDep
  },
  data () {
    return {
      pageCurrent: 1, // 列表分页指定的页码
      pageDataSource: [], // 分页的数据
      dataSourceLength: 0, // 列表数据条数
      description: 'erp_meeting_reservation管理页面',
      // 表头
      columns: [],
      // 列设置
      settingColumns: [],
      // 列定义
      defColumns: [
        {
          title: '日期',
          align: 'center',
          dataIndex: 'date',
          width:100,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            // 日期合并单元格
            obj.attrs.rowSpan = row.rowSpan
            return obj;
          }
        },
        {
          // 2022年11月28日15:40:36 上线前完善 一协同办公 将“所在位置”修改为“会议室名称”
          title: '会议室名称',
          align: 'center',
          dataIndex: 'roomName',
          width:200,
          scopedSlots: { customRender: 'location' },
          ellipsis: true
        },
        {
          title: '管理员',
          align: 'center',
          width:100,
          dataIndex: 'administrator',
          ellipsis: true,
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['person'], text + '')
            }
          }
        },
        {
          title: '8:00-8:59',
          align: 'center',
          dataIndex: '8:00',
          width:100,
          customCell: this.renderTdBackground8,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['8:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '8:00')
            return obj;
          }

        },
        {
          title: '9:00-9:59',
          align: 'center',
          dataIndex: '9:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['9:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '9:00')
            return obj;
          },
          customCell: this.renderTdBackground9
        },
        {
          title: '10:00-10:59',
          align: 'center',
          dataIndex: '10:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['10:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '10:00')
            return obj;
          },
          customCell: this.renderTdBackground10
        },
        {
          title: '11:00-11:59',
          align: 'center',
          dataIndex: '11:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['11:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '11:00')
            return obj;
          },
          customCell: this.renderTdBackground11
        },
        {
          title: '12:00-12:59',
          align: 'center',
          dataIndex: '12:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['12:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '12:00')
            return obj;
          },
          customCell: this.renderTdBackground12
        },
        {
          title: '13:00-13:59',
          align: 'center',
          dataIndex: '13:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['13:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '13:00')
            return obj;
          },
          customCell: this.renderTdBackground13
        },
        {
          title: '14:00-14:59',
          align: 'center',
          dataIndex: '14:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['14:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '14:00')
            return obj;
          },
          customCell: this.renderTdBackground14
        },
        {
          title: '15:00-15:59',
          align: 'center',
          dataIndex: '15:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['15:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '15:00')
            return obj;
          },
          customCell: this.renderTdBackground15
        },
        {
          title: '16:00-16:59',
          align: 'center',
          dataIndex: '16:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['16:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '16:00')
            return obj;
          },
          customCell: this.renderTdBackground16
        },
        {
          title: '17:00-17:59',
          align: 'center',
          dataIndex: '17:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['17:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '17:00')
            return obj;
          },
          customCell: this.renderTdBackground17
        },
        {
          title: '18:00-18:59',
          align: 'center',
          dataIndex: '18:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['18:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '18:00')
            return obj;
          },
          customCell: this.renderTdBackground18
        },
        {
          title: '19:00-19:59',
          align: 'center',
          dataIndex: '19:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['19:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '19:00')
            return obj;
          },
          customCell: this.renderTdBackground19
        },
        {
          title: '20:00-20:59',
          align: 'center',
          dataIndex: '20:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['20:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '20:00')
            return obj;
          },
          customCell: this.renderTdBackground20
        },
        {
          title: '21:00-21:59',
          align: 'center',
          dataIndex: '21:00',
          width:100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {}
            }
            if (value) {
              obj.children = filterMultiDictText(this.dictOptions['person'], row.reservationList[row['21:00'] - 1].applyUser + '') + ',' + row.reservationList[value - 1].meetingTheme
            }
            obj.attrs.colSpan = this.colspanMerge(value, row, index, '21:00')
            return obj;
          },
          customCell: this.renderTdBackground21
        }
      ],
      url: {
        list: '/api/erp/oa/meeting/erpMeetingReservation/list',
        delete: '/api/erp/oa/meeting/erpMeetingReservation/delete',
        deleteBatch: '/api/erp/oa/meeting/erpMeetingReservation/deleteBatch',
        exportXlsUrl: '/api/erp/oa/meeting/erpMeetingReservation/exportXls',
        importExcelUrl: '/api/erp/oa/meeting/erpMeetingReservation/importExcel',
        queryUserDeparts: '/api/erpmng/sys/user/getCurrentUserDeparts'
      },
      dictOptions: {},
      superFieldList: [],
      rangeDate: [],
      applyUserDept: '',
      dataSource: [],
      loading: true
    }
  },
  created() {
    this.initDictConfig();
  },
  computed: {
    userInfo: {
    get() {
      return this.$store.getters.userInfo
    },
    set(newValue) {}
  }
  },
  methods: {
    handleAdd (record, time, index) {
      record = this.dataSource[index]
      record.beginTime = time
      record.applyUserDept = this.applyUserDept
      var endTime = time.indexOf(':')
      var endTimeNumber = Number(time.substring(0, endTime))
      record.endTime = (endTimeNumber + 1) + ':00'
      this.$refs.modalForm.add(record, this.dataSource[index])
    },
    handleEdit (time, record, index) {
      var editIndex = record[time] - 1
      record.beginTime = record.reservationList[editIndex].beginTime
      record.endTime = record.reservationList[editIndex].endTime
      record.applyUserDept = record.reservationList[editIndex].applyUserDept
      record.roomId = record.reservationList[editIndex].roomId
      record.applyDate = record.reservationList[editIndex].applyDate
      record.remark = record.reservationList[editIndex].remark
      record.meetingPrepare = record.reservationList[editIndex].meetingPrepare
      record.meetingTheme = record.reservationList[editIndex].meetingTheme
      record.delFlag = record.reservationList[editIndex].delFlag
      record.attendanceNum = record.reservationList[editIndex].attendanceNum
      record.usePurpose = record.reservationList[editIndex].usePurpose
      record.id = record.reservationList[editIndex].id
      record.beginDate = record.reservationList[editIndex].beginDate
      record.endDate = record.reservationList[editIndex].endDate
      record.attachment = record.reservationList[editIndex].attachment
      console.log('record', record)
      if (this.userInfo.empId !== record.reservationList[editIndex].applyUser && this.userInfo.empId !== record.administrator) {
        this.$message.error('暂无编辑权限！')
        return
      }
      this.$refs.modalForm.edit(record, this.dataSource[index])
    },
    handleDelete (record) {
      record = this.dataSource[0].reservationList[0]
      record.applyUserDept = this.applyUserDept
      record.roomId = this.dataSource[0].id
      record.roomName = this.dataSource[0].roomName
      record.administrator = this.dataSource[0].administrator
      if (this.userInfo.empId !== record.applyUser && this.userInfo.empId !== record.administrator) {
        this.$message.error('暂无删除权限！')
        return
      }
      deleteAction(this.url.delete, { id: record.id }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleChangeRangeDate (dates, dateStrs) {
      this.queryParam.beginDate = dateStrs[0]
      this.queryParam.endDate = dateStrs[1]
    },
    initDictConfig() {
      initDictOptions('erp_employee_file,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'person', res.result)
        }
      })
    },
    loadData () {
      this.loading = true
      isColSpan = 0 // 重置 单元格合并对比值
      isRoomSpan = '' // 重置 单元格合并对比值
      this.pageCurrent = 1 // 列表分页指定的页码
      this.pageDataSource = [] // 分页的数据
      this.dataSourceLength = 0 // 列表数据条数
      getAction(this.url.list, this.queryParam).then(res => {
        if (res.code === 0 && res.result) {
          const roomArr = []
          res.result.forEach((item, index) => {
            var arrLength = item.roomList.length
            item.roomList.forEach((item2, index2) => {
              // 判断合并日期的单元格
              // if (index2 == 0) {
              //   item2.rowSpan = arrLength
              // } else {
              //   item2.rowSpan = 0
              // }
              item2.date = item.date
              item2.beginDate = item.date
              item2.endDate = item.date
              item2.key = index + '' + index2
              if (item2.reservationList && item2.reservationList.length) {
                // 当日期中有预约的
                var appointmentDate = { ...item2 }
                item2.reservationList.forEach((item3, index3) => {
                  var beginTime = item3.beginTime.indexOf(':')
                  var beginTimeNumber = Number(item3.beginTime.substring(0, beginTime))
                  var endTime = item3.beginTime.indexOf(':')
                  var endTimeNumber = Number(item3.endTime.substring(0, endTime))
                  var timeNum = 'timeNum' + (index3 + 1)
                  appointmentDate[timeNum] = endTimeNumber - beginTimeNumber
                  appointmentDate.applyUser = item3.applyUser
                  for (var i = beginTimeNumber; i < endTimeNumber; i++) {
                    var time = i + ':00'
                    appointmentDate[time] = index3 + 1
                    appointmentDate.beginTime = item3.beginTime
                    appointmentDate.endTime = item3.endTime
                    appointmentDate.meetingTheme = item3.meetingTheme
                    appointmentDate.key = item2.key + index3
                  }
                })
                roomArr.push(appointmentDate)
              } else {
                roomArr.push(item2)
              }
            })
          })
          this.dataSourceLength = roomArr.length // 获取处理过的总数据的长度
          this.pageDataSource = this.returnAllPageFunc(10, roomArr) // 获取做成分页的数据

          // 获取当前页的数据
          var dataArr = []
          this.pageDataSource.map(item => {
            if (this.pageCurrent == item.pageNum) {
              dataArr = item.list
            }
          })
          this.timer = setTimeout(() => {
            this.dataSource = this.returnDate(dataArr) // 获取列表的数据
            if (this.timer) {
              clearTimeout(this.timer)
              this.timer = null
            }
          }, 500)
        }
      }).finally(() => {
        this.loading = false
      })
    },

    // 返回日期单元格
    returnDate (arr) {
      // 判断rowSpan的个数
      var newArr = [...new Set(arr.map(i => i.date))] // 数组对象去重
      // 利用二维数组把在同一日期的数据放在一个数组对象里面
      var list = []
      newArr.forEach(i => {
          list.push(arr.filter(t => t.date === i))
      })
      var mlist = []
      // 利用二维数组获取需要合并单元格的数量
      list.forEach((i, index) => {
        i.map((value, val) => {
          if (val == 0) {
            mlist.push({
              ...value,
              rowSpan: i.length
            })
          } else {
            mlist.push({
              ...value,
              rowSpan: 0
            })
          }
        })
      })
      return mlist
    },

    searchQuery () {
      this.loadData()
    },
    searchReset () {
      this.queryParam = {}
      this.rangeDate = []
      this.pageCurrent = 1
      this.searchQuery()
    },

    // 点击分页触发
    handleTableChange (e) {
      this.loading = true

      // 请求数据
      this.timer = setTimeout(() => {
        if (this.timer) {
          clearTimeout(this.timer)
          this.timer = null
        }
        this.loading = false
        if (e.current) {
          this.pageCurrent = e.current
          var dataArr = []
          this.pageDataSource.map(item => {
            if (this.pageCurrent == item.pageNum) {
              dataArr = item.list
            }
          })
        }
        this.dataSource = this.returnDate(dataArr)
      }, 200)
    },

    // 人为假分页
    returnAllPageFunc(pageSize, arr) {
      let pageNum = 1
      let pageObj = {
        pageNum: 1,
        list: []
      }
      let pageResult = []
      let newArr = JSON.parse(JSON.stringify(arr))
      let totalPage = newArr.length ? Math.ceil(arr.length / pageSize) : 0 // 计算总页数 
      for (let i = 1; i <= totalPage; i++) {
        if (totalPage == 1) {
          pageNum += 1
          pageObj.list = newArr.splice(0, arr.length)
        } else if (i <= totalPage) {
          pageNum += 1
          pageObj.list = newArr.splice(0, pageSize)
        } else {
          pageObj.list = newArr.splice(0, arr.length % pageSize)
        }
        pageResult.push(pageObj)
        pageObj = {
          pageNum: pageNum,
          list: []
        }
      }
      return pageResult
    },

    handleShowRoomDetail (record) {
      this.$refs.roomModalForm.edit(record);
      this.$refs.roomModalForm.title = '会议室详情';
      this.$refs.roomModalForm.disableSubmit = true;
    },

    // 修改预约成功的颜色
    renderTdBackground8(record, index, value) {
      return this.renderTdBackground('8:00', record, index)
    },
    renderTdBackground9(record, index) {
        return this.renderTdBackground('9:00', record, index)
    },
    renderTdBackground10(record, index) {
        return this.renderTdBackground('10:00', record, index)
    },
    renderTdBackground11(record, index) {
        return this.renderTdBackground('11:00', record, index)
    },
    renderTdBackground12(record, index) {
        return this.renderTdBackground('12:00', record, index)
    },
    renderTdBackground13(record, index) {
        return this.renderTdBackground('13:00', record, index)
    },
    renderTdBackground14(record, index) {
        return this.renderTdBackground('14:00', record, index)
    },
    renderTdBackground15(record, index) {
        return this.renderTdBackground('15:00', record, index)
    },
    renderTdBackground16(record, index) {
        return this.renderTdBackground('16:00', record, index)
    },
    renderTdBackground17(record, index) {
        return this.renderTdBackground('17:00', record, index)
    },
    renderTdBackground18(record, index) {
        return this.renderTdBackground('18:00', record, index)
    },
    renderTdBackground19(record, index) {
        return this.renderTdBackground('19:00', record, index)
    },
    renderTdBackground20(record, index) {
        return this.renderTdBackground('20:00', record, index)
    },
    renderTdBackground21(record, index) {
        return this.renderTdBackground('21:00', record, index)
    },
    // 渲染有数据的单元格的颜色
    renderTdBackground (time, record, index) {
      if (record.roomStatus != 0) {
        return {
          // 这个style就是我自定义的属性，也就是官方文档中的props
          style: {
              // 行背景色
              'background-color': 'gray'
          },
          // 编辑事件
          on: {
              // 鼠标单击行
              click: event => {
                  this.$message.warning('暂不可使用')
              }
          }
        }
      }
      if (record[time]) {
        return {
          // 这个style就是我自定义的属性，也就是官方文档中的props
          style: {
              // 行背景色
              'background-color': 'orange'
          },
          // 编辑事件
          on: {
              // 鼠标单击行
              click: event => {
                  this.handleEdit(time, record, index)
              }
          }
        }
      }
      return {
          style: {
              // 行背景色
              'cursor': 'pointer'

          },
          // 添加事件
          on: {
              // 鼠标单击行
              click: event => {
                  this.handleAdd(record, time, index)
              }
          }
      }
    },

    // 获取单元格合并
    colspanMerge(value, row, index, time) {
      if (value) {
        var colNum = 0
        if (isColSpan == value && isRoomSpan == row.id) {
          colNum = 0
        } else if (isColSpan != value || isRoomSpan != row.id) { // 当前的会议室和下一个会议室不想等或者当前
          isColSpan = value
          isRoomSpan = row.id
          var num = row[time]
          var timeNum = 'timeNum' + num
          colNum = row[timeNum]
        }
        return colNum
      } else {
        isColSpan = 0
        isRoomSpan = ''
      }
    }
  }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
